const DB = require('../../../utils/db')
// 引入jwt token工具
const JwtUtil = require('../../../utils/jwt')
/**
 * GET
 * 根据自己的id,获取好友列表,并且查询出哪些好友和自己聊过天，查出最后一句聊天内容
 */

module.exports = async (ctx) => {
  // 获取token
  let token = ctx.request.header.authorization
  let jwt = new JwtUtil(token)
  // 用token获取到userid
  let userid = jwt.verifyToken()
  // 查询好友列表
  const friendList = await DB.query(
    `select uf.friendid, u.username, u.avatar from user_friend uf join user u on uf.friendid = u.userid where uf.userid='${userid}';`
  )
  // 查询群聊列表
  const groupList = await DB.query(
    `select ug.groupid, g.groupName, g.introduction, g.announcement, g.lord from user_group ug join \`group\` g on ug.groupid = g.groupid where ug.userid='${userid}';`
  )
  // 所有的聊天记录
  let allMessageList = []
  for (let item of friendList) {
    let messageList
    if (item.friendid) {
      // asc从小排到大，升序
      messageList = await DB.query(
        `select fm.*, fromUser.username as fromName, toUser.username as toName, fromUser.avatar as fromAvatar, toUser.avatar as toAvatar
             from friend_message fm JOIN user fromUser ON fromUser.userid = fm.fromid
             JOIN user toUser on toUser.userid = fm.toid where (fm.fromid='${userid}' AND fm.toid='${item.friendid}') OR (fm.fromid='${item.friendid}' AND fm.toid='${userid}') order by createTime asc`
      )
      // 筛选出未读信息，然后计算条数，传一个unReadNumber
      let unReadNumber = 0
      for (let item of messageList) {
        if ((item.readStatus = 0)) {
          unReadNumber++
        }
      }
      if (messageList.length > 0){
             allMessageList.push({
               ...messageList[messageList.length - 1],
               unReadNumber,
             })
      }
   
    }
  }
  for (let item of groupList) {
    let messageList
    if (item.groupid) {
      // asc从小排到大，升序
      messageList = await DB.query(
        `select gm.*, fromUser.username as fromName, toUser.username as toName, fromUser.avatar as fromAvatar, toUser.avatar as toAvatar, g.groupName as groupName
             from group_message gm JOIN user fromUser ON fromUser.userid = gm.userid
             JOIN user toUser on toUser.userid = gm.userid JOIN \`group\` g on g.groupid='${item.groupid}' where ( gm.groupid='${item.groupid}') order by id asc`
      )
      let unReadNumber = 0
      for (let item of messageList) {
        if ((item.readStatus = 0)) {
          unReadNumber++
        }
      }
      if (messageList.length > 0) {
        allMessageList.push({
          ...messageList[messageList.length - 1],
          unReadNumber,
        })
      }
    }
  }
  ctx.body = {
    code: 0,
    data: allMessageList,
  }
}
